﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class DelUserHandler : IRequestHandler<DelUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IMapper mapper;

        public DelUserHandler(IBaseRepository<UserModel> userRepo, IMapper mapper)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var user = userRepo.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            if (user == null)
            {
                res.Msg = "用户不存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            user = mapper.Map(request, user);
            user.IsDelete = true;
            int i = userRepo.Update(user);
            if (i > 0)
            {
                res.Msg = "删除成功";
                res.Code = ApiEnum.Success;
                res.Data = i;
            }
            else
            {
                res.Msg = "删除失败";
                res.Code = ApiEnum.Error;
                res.Data = i;
            }
            return Task.FromResult(res);
        }
    }
}
